package com.bdqn.gulimall.order.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bdqn.common.utils.PageUtils;
import com.bdqn.common.utils.Query;
import com.bdqn.common.utils.R;
import com.bdqn.common.vo.MemberRespVo;
import com.bdqn.gulimall.order.constant.OrderConstant;
import com.bdqn.gulimall.order.dao.OrderDao;
import com.bdqn.gulimall.order.entity.OrderEntity;
import com.bdqn.gulimall.order.entity.OrderItemEntity;
import com.bdqn.gulimall.order.feign.CartFeignService;
import com.bdqn.gulimall.order.feign.MemberFeignService;
import com.bdqn.gulimall.order.feign.WmsFeignService;
import com.bdqn.gulimall.order.interceptor.LoginUserInterceptor;
import com.bdqn.gulimall.order.service.OrderItemService;
import com.bdqn.gulimall.order.service.OrderService;
import com.bdqn.gulimall.order.to.OrderCreateTo;
import com.bdqn.gulimall.order.vo.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 使用RabbitMQ
 * 1.引入amqp场景；RabbitAutoConfiguration就会自动生效
 * <p>
 * <p>
 * 会给容器中自动配置 RabbitTemplate、AmqpAdmin、CachingConnectionFactory（连接工厂）、RabbitMessagingTemplate
 * 所有的属性都在
 *
 * @ConfigurationProperties(prefix = "spring.rabbitmq")
 * public class RabbitProperties 里面绑定
 * <p>
 * 2.@EnableRabbit
 */
@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    private ThreadLocal<OrderSubmitVo> confirmVoThreadLocal = new ThreadLocal<>();

    @Resource
    MemberFeignService memberFeignService;

    @Resource
    OrderItemService orderItemService;

    @Resource
    CartFeignService cartFeignService;

    @Resource
    ThreadPoolExecutor executor;

    @Resource
    WmsFeignService wmsFeignService;

    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(new Query<OrderEntity>().getPage(params), new QueryWrapper<OrderEntity>());

        return new PageUtils(page);
    }

    /**
     * 获取当前订单的支付信息
     *
     * @return
     */
    @Override
    public PayVo getOrderPay(String orderSn) {
        /**
         * 订单的支付信息
         */
        PayVo payVo = new PayVo();
        OrderEntity order = this.getById(orderSn);

        /**
         * 处理decimal（四位小数）类型的数据，支付宝只保留两位小数
         * ROUND_UP向上取值，防止第四位小数有值，如果有，则取上一位
         */
        BigDecimal bigDecimal = order.getPayAmount().setScale(2, BigDecimal.ROUND_UP);
        payVo.setTotal_amount(bigDecimal.toString());
        payVo.setOut_trade_no(order.getOrderSn());//订单号（对外交易号）

        //查询订单项的信息
        List<OrderItemEntity> order_sn = orderItemService.
                list(new QueryWrapper<OrderItemEntity>().eq("order_sn", orderSn));
        OrderItemEntity entity = order_sn.get(0);
        payVo.setSubject(entity.getSkuName());
        payVo.setBody(entity.getSkuAttrsVals());//SkuAttrsVals:商品销售属性
        return payVo;
    }

    /**
     * 查出订单详情数据
     *
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPageWithItem(Map<String, Object> params) {
        MemberRespVo memberResponseVo = LoginUserInterceptor.loginUser.get();
        IPage<OrderEntity> page = this.page(new Query<OrderEntity>().getPage(params),
                //member_id 会员id
                new QueryWrapper<OrderEntity>().eq("member_id", memberResponseVo.getId()).
                        //id 订单号
                                orderByDesc("id")
        );
        //每一个订单
        List<OrderEntity> order_sn = page.getRecords().stream().map(order -> {
            // 所有订单项（详情信息）
            List<OrderItemEntity> itemEntities = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", order.getOrderSn()));
            order.setItemEntities(itemEntities);

            return order;
        }).collect(Collectors.toList());

        page.setRecords(order_sn);


        return new PageUtils(page);
    }

    @Override
    public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {
        OrderConfirmVo confirmVo = new OrderConfirmVo();
        //1、远程查询所有的收获地址列表
        //返回出当前登录的对象
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();

        System.out.println("MemberRespVo memberRespVo"+JSON.toJSONString(memberRespVo));
        //异步执行
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        //因为异步线程是不一样的，所以会丢失请求数据，需要设置一下请求数据

        CompletableFuture<Void> getAddressFuture = CompletableFuture.runAsync(() -> {
            //为了防止丢失请求数据，设置一下请求的各种参数
            RequestContextHolder.setRequestAttributes(requestAttributes);
            //通过调用远程服务传入当前对象的id并且拿到收货地址
            List<MemberAddressVo> address = memberFeignService.getAddress(memberRespVo.getId());
            confirmVo.setMemberAddressVos(address);
        }, executor);

        CompletableFuture<Void> cartFuture = CompletableFuture.runAsync(() -> {
            //为了防止丢失请求数据，设置一下请求的各种参数
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<OrderItemVo> currentUserCartItems = cartFeignService.getCurrentUserCartItems();
            //2、远程查询购物车所有选中的购物项
            confirmVo.setItems(currentUserCartItems);
        }, executor).thenRunAsync(()->{
            //查询是否还有库存
            List<OrderItemVo> items = confirmVo.getItems();
            //获取商品id
            List<Long> collect = items.stream().map(item -> item.getSkuId()).collect(Collectors.toList());

            R stock = wmsFeignService.getSkusHasStock(collect);
            List<SkuStockVo> data = stock.getData(new TypeReference<List<SkuStockVo>>(){});
            if(data!=null){
                //便利商品，并且查询里面是否有货
                Map<Long, Boolean> map = data.stream().collect(Collectors.toMap(SkuStockVo::getSkuId, SkuStockVo::getHasStock));
                confirmVo.setStocks(map);
            }
        },executor);


        //3.查询用户积分,并且设置
        confirmVo.setIntegration(memberRespVo.getIntegration());

        //4.其他数据自动计算

        //5. TODO: 2022/3/10 0010 防重复令牌
        String token = UUID.randomUUID().toString().replace("-", "");

        stringRedisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX+memberRespVo.getId(),token,30, TimeUnit.MINUTES);

        confirmVo.setOrderToken(token);
        CompletableFuture.allOf(getAddressFuture,cartFuture).get();

        return confirmVo;
    }

    /**
     * 下单操作
     *
     * @param vo
     * @return
     */
    @Override
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo vo) {
        confirmVoThreadLocal.set(vo);
        SubmitOrderResponseVo response = new SubmitOrderResponseVo();
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();

        //1.验证令牌【令牌的对比和删除必须保证原子性】
        //0验证令牌失败 1.删除成功
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        String orderToken = vo.getOrderToken();
        //原子验证令牌和删除令牌
        Long result = stringRedisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId()), orderToken);
        if(result==0L){
            //令牌验证失败
            response.setCode(1);
            return response;
        }else{
            //令牌验证成功
            //下单:去创建订单，验令牌，验价格，锁库存。。。
            OrderCreateTo order = createOrder();
        }
//        String redisToken = stringRedisTemplate.opsForValue().get(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId());
//        if(orderToken!=null && redisToken.equals(orderToken)){
//            //令牌验证成功
//        }else{
//            //令牌验证失败
//        }

        return response;
    }

    /**
     * 处理支付结果
     *
     * @param vo
     * @return
     */
    @Override
    public String handlePayResult(PayAsyncVo vo) {
        return null;
    }

    private OrderCreateTo createOrder(){
        OrderCreateTo createTo = new OrderCreateTo();
        //1、生成一个订单号
        String orderSn = IdWorker.getTimeId();
        //创建订单号
        OrderEntity entity = new OrderEntity();
        entity.setOrderSn(orderSn);
        //获取收获地址信息
        OrderSubmitVo orderSubmitVo = confirmVoThreadLocal.get();
        R fare = wmsFeignService.getFare(orderSubmitVo.getAddrId());
        FareVo fareResp = fare.getData(new TypeReference<FareVo>() {
        });
        //运费
        entity.setFreightAmount(fareResp.getFare());
        //城市
        entity.setReceiverCity(fareResp.getAddress().getCity());

        entity.setReceiverDetailAddress(fareResp.getAddress().getDetailAddress());

        return createTo;
    }




}
